package com.too.learn.drools.util;

import cn.hutool.core.lang.Filter;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import lombok.Data;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 解析Custo文件
 *
 * @Description
 * @Author ouyf
 * @Date 2024/7/15
 * <p>
 * Copyright (c) Siemens Mobility TBDS 2024, All Rights Reserved, Confidential
 */
public class CustoParseUtil {

    static String custoFZL1 = "C:\\data\\ouyf\\07_项目\\05_tbds\\SIL2\\30需求\\11实时监控\\10需求文档\\FZL1_custo.json";
    static String custoNJS6 = "D:/siemens/nas-lab/01_TBDS_系统设计/01_TBDS_轨旁需求/CustoRead/JSON/NJS6CLOUD_custo.json";
    static String custoCQL1 = "D:/siemens/nas-lab/01_TBDS_系统设计/01_TBDS_轨旁需求/项目元件配置及名称/CQL1_EXT_custo.json";
    static String custoXAL3 = "D:/siemens/nas-lab/01_TBDS_系统设计/01_TBDS_轨旁需求/项目元件配置及名称/XAL3_custo.json";
    static String custoFSL3 = "D:/siemens/nas-lab/01_TBDS_系统设计/01_TBDS_轨旁需求/CustoRead/JSON/FSL3_custo.json";
    static String custoFZL5 = "D:/Tools/deploy/FZL5_custo_pretty.json";
    static String custoHFL2 = "D:\\ouyf\\06_NAS\\SynologyDrive\\01_TBDS_系统设计\\01_TBDS_轨旁需求\\项目元件配置及名称\\HFL2_custo.json";

    // 对应项目的json格式custo文件
    public static List<Map<String, Object>> custo;

    // custo中部分属性的字典
    public static Map<String, Object> custoDict;

/*    static {
        try {
            eleId2("C:\\data\\ouyf\\07_项目\\05_tbds\\SIL2\\30需求\\11实时监控\\09源文件\\FZL1_custo.json");
            custoDictParse("C:\\data\\ouyf\\07_项目\\05_tbds\\SIL2\\30需求\\11实时监控\\09源文件\\custo-dict.json");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }*/

    public static void main(String[] args) throws Exception {
//		eleId(custoCQL1);
//		eleId(custoNJS6);
//		eleId(custoFZL5);
//		eleId(custoFZL1);

        /*long start = System.currentTimeMillis();
        TreeMap<String, Map<String, Map<String, String>>> map = eleId(custoFZL1);
        System.out.println("耗时：" + (System.currentTimeMillis() - start) + "ms");
        System.out.println(new Gson().toJson(map));*/

        System.out.println(getSegName(2354));

        custoDictParse("C:\\data\\ouyf\\07_项目\\05_tbds\\SIL2\\30需求\\11实时监控\\09源文件\\custo-dict.json");
        System.out.println(custoDict);
    }

    @Data
    static class Cus {
        String elementID;
        String elementType;
        String elementType_name;
        String elementType_tbds;
        String name;
        String name_tbds;
        String simis_pc;
    }

    public static void eleId2(String custoPath) throws Exception {
        File custo = new File(custoPath);
//        System.out.println(custo.exists());
//        assert !custo.exists() : "文件不存在：" + custoPath;
        FileInputStream fis = new FileInputStream(custo);
        byte[] buffer = new byte[fis.available()];
        IOUtils.readFully(fis, buffer);
        String str = new String(buffer);
        Gson gson = new Gson();
        CustoParseUtil.custo = gson.fromJson(str, List.class);
    }

    public static void custoDictParse(String custoDictPath) throws Exception {
        File custo = new File(custoDictPath);
//        assert !custo.exists() : "文件不存在：" + custoDictPath;
        FileInputStream fis = new FileInputStream(custo);
        byte[] buffer = new byte[fis.available()];
        IOUtils.readFully(fis, buffer);
        String str = new String(buffer);
        Gson gson = new Gson();
        custoDict = gson.fromJson(str, Map.class);
    }

    /**
     * 解析Custo文件
     *
     * @param custoPath
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static TreeMap<String, Map<String, Map<String, String>>> eleId(String custoPath) throws Exception {
        File custo = new File(custoPath);
        assert !custo.exists() : "文件不存在：" + custoPath;
        FileInputStream fis = new FileInputStream(custo);
        byte[] buffer = new byte[fis.available()];
        IOUtils.readFully(fis, buffer);
        String str = new String(buffer);
        Gson gson = new Gson();
        List<LinkedTreeMap> json = gson.fromJson(str, List.class);
        Map<String, Map<String, Map<String, String>>> jmap = new HashMap<>();
        json.forEach(c -> {
            Object simisPC = c.get("simis_pc");
            if (simisPC != null && StringUtils.isNotBlank(simisPC.toString())) {
                String simis = simisPC.toString();
                Map<String, Map<String, String>> mapSimisPc = jmap.get(simis);
                if (mapSimisPc == null) {
                    jmap.put(simis, mapSimisPc = new HashMap<>());
                }
                String eleType = c.get("elementType").toString();
                Map<String, String> typeMap = mapSimisPc.get(eleType);
                if (typeMap == null) {
                    mapSimisPc.put(eleType, typeMap = new HashMap<>());
                }
                String eleId = c.get("elementID").toString();
                String val = c.get("name_tbds").toString();
                typeMap.put(eleId, val);
            }
        });
        TreeMap<String, Map<String, Map<String, String>>> sortMap = new TreeMap<>();
        sortMap.putAll(jmap);
        return sortMap;
    }

    /**
     * 根据elementType和elementId获取name_tbds
     *
     * @param elementType :
     * @param elementId   :
     * @return : java.lang.String
     * @author : ouyf
     * @date : 2024/11/8
     */
    public static String getTbdsName(Integer elementType, Integer elementId) {
        if (custo == null) {
            return null;
        }
        Map<String, Object> obj = custo.stream().filter(map
                -> elementType.equals(MapUtils.getInteger(map, "elementType")) &&
                elementId.equals(MapUtils.getInteger(map, "elementID"))).findAny().orElse(null);
        if (obj != null) {
            return MapUtils.getString(obj, "name_tbds");
        }
        return null;
    }

    /**
     * 将PTID结尾的属性值转换为custo文件中的name_tbds
     *
     * @param oos :
     * @return : void
     * @author : ouyf
     * @date : 2024/11/11
     */
    public static void transPtId2Name(Map<String, Object> oos) {
        Map<String, Object> ptidMap = cn.hutool.core.map.MapUtil.filter(oos, new Filter<Map.Entry<String, Object>>() {
            @Override
            public boolean accept(Map.Entry<String, Object> stringStringEntry) {
                if (StringUtils.isNotBlank(stringStringEntry.getKey())
                        && stringStringEntry.getKey().endsWith("PTID")
                        && MapUtils.getIntValue(oos, stringStringEntry.getKey()) != 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (MapUtils.isNotEmpty(ptidMap)) {
            ptidMap.keySet().forEach(keyPTID -> {
                Integer valuePTID = MapUtils.getIntValue(oos, keyPTID);
                oos.put(keyPTID, getTbdsName(16, valuePTID));
            });
        }
    }

    /**
     * 将OBCUID结尾的属性值转换为custo文件中的name_tbds
     *
     * @param oos :
     * @return : void
     * @author : ouyf
     * @date : 2024/11/11
     */
    public static void transObcuId2Name(Map<String, Object> oos) {
        Map<String, Object> filterMap = cn.hutool.core.map.MapUtil.filter(oos, new Filter<Map.Entry<String, Object>>() {
            @Override
            public boolean accept(Map.Entry<String, Object> stringStringEntry) {
                if (StringUtils.isNotBlank(stringStringEntry.getKey())
                        && stringStringEntry.getKey().endsWith("OBCUID")
                        && MapUtils.getIntValue(oos, stringStringEntry.getKey()) != 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (MapUtils.isNotEmpty(filterMap)) {
            filterMap.keySet().forEach(key -> {
                Integer value = MapUtils.getIntValue(oos, key);
                oos.put(key, getTbdsName(154, value));
            });
        }
    }

    /**
     * 将SegID结尾的属性值进行转换
     *
     * @param oos :
     * @return : void
     * @author : ouyf
     * @date : 2024/11/11
     */
    public static void transSegId(Map<String, Object> oos) {
        Map<String, Object> ptidMap = cn.hutool.core.map.MapUtil.filter(oos, new Filter<Map.Entry<String, Object>>() {
            @Override
            public boolean accept(Map.Entry<String, Object> stringStringEntry) {
                if (StringUtils.isNotBlank(stringStringEntry.getKey())
                        && stringStringEntry.getKey().endsWith("SegID")
                        && MapUtils.getIntValue(oos, stringStringEntry.getKey()) != 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (MapUtils.isNotEmpty(ptidMap)) {
            ptidMap.keySet().forEach(keyPTID -> {
                Integer valuePTID = MapUtils.getIntValue(oos, keyPTID);
                oos.put(keyPTID, getSegName(valuePTID));
            });
        }
    }

    /**
     * 根据SegID获取区段名称
     *
     * @param segId
     * @return
     */
    public static String getSegName(Integer segId) {
        Integer lineNumber = segId / 2048;
        Integer lineSection = segId % 2048 / 256;
        Integer segmentNumber = segId % 256;
        return String.format("L%02d%d%03d", lineNumber, lineSection, segmentNumber);
    }

    /**
     * 根据CustoDict翻译属性值
     *
     * @param key
     * @param subKey
     * @return
     */
    public static String getDescFromCustoDict(String key, Integer subKey) {
        if (MapUtils.isNotEmpty(custoDict)) {
            Map<String, Object> subMap = (Map<String, Object>) custoDict.get(key);
            if (MapUtils.isNotEmpty(subMap)) {
                return MapUtils.getString(subMap, subKey.toString());
            }
        }
        return null;
    }

    /**
     * 根据CustoDict翻译属性值
     *
     * @param orginMap 将指定的map中对应的key和subKey的值翻译为custoDict定义的描述
     * @return
     */
    public static void transMapWithCustoDict(Map orginMap) {
        if (MapUtils.isNotEmpty(custoDict) && MapUtils.isNotEmpty(orginMap)) {
            custoDict.forEach((key, value) -> {
                Integer subKey = MapUtils.getInteger(orginMap, key);
                if (subKey != null) {
                    String desc = getDescFromCustoDict(key, subKey);
                    orginMap.put(key, desc);
                }
            });

            System.out.println("transMapWithCustoDict=" + new Gson().toJson(orginMap));
        }
    }
}
